package com.shanzmoo.db.sys.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.shanzmoo.base.bean.PageRespBase;
import com.shanzmoo.base.constant.Constant;
import com.shanzmoo.base.bean.SResponse;
import com.shanzmoo.base.exception.LogicRepeatCheckException;
import com.shanzmoo.db.sys.entity.OutletInfoEntity;
import com.shanzmoo.db.sys.entity.dto.OutletInfoQueryDto;
import com.shanzmoo.db.sys.entity.dto.OutletInfoSaveDto;
import com.shanzmoo.db.sys.entity.dto.OutletInfoUpdateDto;
import com.shanzmoo.db.sys.entity.vo.OutletInfoPageVo;
import com.shanzmoo.db.sys.entity.vo.OutletInfoSelectVo;
import com.shanzmoo.db.sys.mapper.OutletInfoMapper;
import com.shanzmoo.db.sys.service.IOutletInfoService;
import com.shanzmoo.db.sys.service.ISysParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 门店信息 服务实现类
 * </p>
 *
 * @author Gzhao
 * @since 2020-12-09
 */
@Service
public class OutletInfoServiceImpl extends ServiceImpl<OutletInfoMapper, OutletInfoEntity> implements IOutletInfoService {
    @Autowired
    private ISysParamService sysParamService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public SResponse<Boolean> add(OutletInfoSaveDto saveDto, Integer currentUserId) {
        // 校验门店名称是否重复
        checkName(saveDto.getName());

        OutletInfoEntity infoEntity = saveDto.convert(currentUserId);
        // 生成订单号标记
        infoEntity.setMark(sysParamService.getOutletMark());

        baseMapper.insert(infoEntity);
        return SResponse.ok(Boolean.TRUE);
    }

    @Override
    public SResponse<Boolean> deleteById(Integer outletId, Integer currentUserId) {
        // 1. 校验门店下无订单信息
        boolean hasOrder = baseMapper.checkHasOrder(outletId);
        if (hasOrder){
            return  SResponse.fail(Constant.ERRCODE_LOGIC, "当前门店已产生订单数据，不允许删除");
        }
        // 2. 校验门店下无人员信息
        boolean hasUser = baseMapper.checkHasUser(outletId);
        if (hasUser){
            return  SResponse.fail(Constant.ERRCODE_LOGIC, "当前门店有用户数据，不允许删除");
        }

        OutletInfoEntity outletInfo = OutletInfoEntity.builder()
                .id(outletId)
                .deleted(true)
                .updateUser(currentUserId)
                .build();
        baseMapper.updateById(outletInfo);

        return SResponse.ok(Boolean.TRUE);
    }

    @Override
    public SResponse<Boolean> edit(OutletInfoUpdateDto updateDto, Integer currentUserId) {
        OutletInfoEntity old = baseMapper.selectById(updateDto.getId());

        old.setName(updateDto.getName());
        old.setUpdateUser(currentUserId);
        old.setRemark(updateDto.getRemark());

        baseMapper.updateById(old);
        return SResponse.ok(Boolean.TRUE);
    }

    @Override
    public SResponse<PageRespBase<OutletInfoPageVo>> getPageList(OutletInfoQueryDto queryDto) {
        // 开启分页
        Page page = PageHelper.startPage(queryDto.getPageNum(), queryDto.getPageSize());
        List<OutletInfoEntity> list = baseMapper.selectList(
                new QueryWrapper<OutletInfoEntity>()
                        .like(StrUtil.isNotBlank(queryDto.getName()), "`name`",
                                StrUtil.isNotBlank(queryDto.getName())?queryDto.getName().trim() : "")
                        .eq("deleted", false)
                        .orderByAsc("id")
        );

        List<OutletInfoPageVo> reList = list.stream().map(e -> {
            return OutletInfoPageVo.create(e);
        }).collect(Collectors.toList());

        PageRespBase<OutletInfoPageVo> re = PageRespBase.create(page, reList);
        PageHelper.clearPage();
        return SResponse.ok(re);
    }

    @Override
    public List<OutletInfoSelectVo> selectList(Integer outletId) {
        List<OutletInfoEntity> list = baseMapper.selectList(
                new QueryWrapper<OutletInfoEntity>()
                        .eq("deleted", false)
                        .in(ObjectUtil.equal(outletId, 1), "id",  1)
                        .eq(ObjectUtil.isNotNull(outletId) && outletId > 1, "id",  outletId)
                        .orderByAsc("id")
        );
        return list.stream().map(e->{
            return OutletInfoSelectVo.create(e);
        }).collect(Collectors.toList());
    }

    /**
     * 校验门店名称
     *
     * @param name
     */
    private void checkName(String name) {
        List<OutletInfoEntity> checkNameList = baseMapper.selectList(
                new QueryWrapper<OutletInfoEntity>()
                        .eq("deleted", false)
                        .eq("name", name)
        );
        if (CollectionUtil.isNotEmpty(checkNameList)) {
            throw new LogicRepeatCheckException("门店名称重复，请重新填写");
        }
    }
}
